package com.liujie.filter;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.liujie.common.BaseContext;
import com.liujie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//登录检查的过滤器
@WebFilter(filterName = "LoginCheckFilter",urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {
    private static final AntPathMatcher antPathMatcher=new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request=(HttpServletRequest) servletRequest;
        HttpServletResponse response=(HttpServletResponse) servletResponse;

        //1.获取访问路径
        String requestURI = request.getRequestURI();
        log.info("本次请求路径，{}",requestURI);

        //2.设定不拦截的路径
        String[] urls={
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/user/login",
                "/user/loginEmail",
                "/user/sendMsg",
                "/user/sendEmailMsg",
        };

        //3.路径过滤
        boolean check = check(urls, requestURI);

        //4.不需要处理，放行
        if (check){
            filterChain.doFilter(request,response);
            return;
        }

        //5.1.判断是否登录，登录就放行
        Long employeeId = (Long) request.getSession().getAttribute("employee");
        if (employeeId!=null){
            BaseContext.setCurrentId(employeeId);
            filterChain.doFilter(request,response);
            return;
        }

        //5.2.判断移动端是否登录
        Long userId = (Long) request.getSession().getAttribute("user");
        if (userId!=null){
            BaseContext.setCurrentId(userId);
            filterChain.doFilter(request,response);
            return;
        }

        //6.未登录
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));

    }

    public boolean check(String[] urls,String requestURI){
        for (String url : urls) {
            if (antPathMatcher.match(url,requestURI)){
                return true;
            }
        }
        return false;
    }
}
